# -*- coding: utf-8 -*-

from odoo import fields, api
from odoo_contrib import models as contrib_models


class Article(contrib_models.SchemaModel):
    _name = 'exhibition.article'
    _description = 'Article for exhibition APP'
    _order = 'create_date desc'
    _rec_name = 'title'

    title = fields.Char(string='标题', required=True)
    content = fields.Html(string='内容', required=True)
    view_count = fields.Integer(string='浏览次数', default=0)

    image = fields.Binary(
        string='标题图',
        attachment=True,
        help='标题图，在微信小程序浏览文章列表时，将与文章标题一同展现'
    )
    image_id = fields.Integer(compute='_compute_image_id')

    video = fields.Binary(
        string='文章视频',
        attachment=True,
    )
    video_filename = fields.Char(string='视频文件名')

    enabled = fields.Boolean(string='是否发布', default=True)

    editor_id = fields.Many2one(
        'exhibition.users',
        string='文章编辑',
    )

    editor_res_user_id = fields.Many2one(
        'res.users',
    )

    editor_name = fields.Char(string='编辑', related='editor_id.name')

    @api.one
    @api.depends('image')
    def _compute_image_id(self):
        self.ensure_one()
        attachment = self.env['ir.attachment'].search([
            ('res_model', '=', 'exhibition.article'),
            ('res_field', '=', 'image'),
            ('res_id', '=', self.id)
        ], limit=1)
        self.image_id = attachment.id

    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            vals['editor_res_user_id'] = self.env.uid
            exhibition_user = self.env['exhibition.users'].search([
                ('res_user_id', '=', self.env.uid)
            ], limit=1)
            vals['editor_id'] = exhibition_user.id
        return super().create(vals_list)

    @api.multi
    def unlink(self):
        for article in self:
            article.enabled = False
        return True

    @api.multi
    def toggle_enabled(self):
        for article in self:
            article.enabled = not article.enabled

    @api.multi
    def been_viewed(self):
        for article in self:
            article.sudo().write({'view_count': article.view_count + 1})
